package com.yh.concert.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import com.yh.concert.domain.YhMerchart;
import com.yh.concert.domain.dto.SiteDto;
import com.yh.concert.service.IYhMerchartService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.yh.concert.domain.YhSite;
import com.yh.concert.service.IYhSiteService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
 * 场地信息Controller
 *
 * @author yh
 * @date 2025-02-26
 */
@Api(tags="场地信息管理")
@RestController
@RequestMapping("/concert/site")
public class YhSiteController extends BaseController
{
    @Autowired
    private IYhSiteService yhSiteService;


    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IYhMerchartService merchartService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询场地信息列表
     */
    @ApiOperation("查询场地信息列表")
    @PreAuthorize("@ss.hasPermi('concert:site:list')")
    @GetMapping("/list")
    public TableDataInfo list(YhSite yhSite)
    {
        startPage();

        // 根据用户身份查询
        LoginUser loginUser = getLoginUser();
        if (loginUser.getUser().getUserId() == 1 || sysUserRoleMapper.isSysAdmin(loginUser.getUserId()) == 1){
            // 超级管理员
           yhSite.setUserId(null);
        }else {
            yhSite.setUserId(loginUser.getUserId());
        }
        List<YhSite> list = yhSiteService.selectYhSiteList(yhSite);
        List<SiteDto> siteDtos = new ArrayList<>();
        // 查询对应的商户名及用户名
        for (YhSite site : list) {
            SiteDto siteDto = new SiteDto();
            YhMerchart one = merchartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getId, site.getMerchartId()));
            if (BeanUtil.isNotEmpty(one)){
                BeanUtil.copyProperties(site, siteDto);
                siteDto.setMerchartName(one.getMerchartName());
                // 获取用户名
                SysUser sysUser = sysUserService.selectUserById(site.getUserId());
                if (BeanUtil.isNotEmpty(sysUser)){
                    siteDto.setUserName(sysUser.getUserName());
                    siteDtos.add(siteDto);
                }

            }

        }

        return getDataTable(siteDtos);
    }

    /**
     * 导出场地信息列表
     */
    @ApiOperation("导出场地信息列表")
    @PreAuthorize("@ss.hasPermi('concert:site:export')")
    @Log(title = "场地信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YhSite yhSite)
    {
        List<YhSite> list = yhSiteService.selectYhSiteList(yhSite);
        ExcelUtil<YhSite> util = new ExcelUtil<YhSite>(YhSite.class);
        util.exportExcel(response, list, "场地信息数据");
    }

    /**
     * 获取场地信息详细信息
     */
    @ApiOperation("获取场地信息详细信息")
    @PreAuthorize("@ss.hasPermi('concert:site:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        YhSite byId = yhSiteService.getById(id);
        SiteDto siteDto = new SiteDto();
        if (BeanUtil.isNotEmpty(byId)){
            BeanUtil.copyProperties(byId,siteDto);
            // 获取商户名
            YhMerchart one = merchartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getId, byId.getMerchartId()));
            if (BeanUtil.isNotEmpty(one)){
                siteDto.setMerchartName(one.getMerchartName());
            }
            // 获取用户名
            SysUser sysUser = sysUserService.selectUserById(byId.getUserId());
            if (BeanUtil.isNotEmpty(sysUser)){
                siteDto.setUserName(sysUser.getUserName());
            }
        }
        return AjaxResult.success(siteDto);
    }

    /**
     * 新增场地信息
     */
    @ApiOperation("新增场地信息")
    @PreAuthorize("@ss.hasPermi('concert:site:add')")
    @Log(title = "场地信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YhSite yhSite)
    {

        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        // 根据userId获取用户信息
        SysUser sysUser = sysUserService.selectUserById(userId);
        // 根据userId获取商户信息
        YhMerchart one = merchartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getUserId, userId));
        if (one == null) {
            return AjaxResult.error("操作失败系统错误");
        }
        yhSite.setUserId(userId);
        yhSite.setMerchartId(one.getId());
        yhSite.setStatus(0);
        return toAjax(yhSiteService.save(yhSite));
    }

    /**
     * 修改场地信息
     */
    @ApiOperation("修改场地信息")
    @PreAuthorize("@ss.hasPermi('concert:site:edit')")
    @Log(title = "场地信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YhSite yhSite)
    {
        return toAjax(yhSiteService.updateById(yhSite));
    }

    /**
     * 删除场地信息
     */
    @ApiOperation("删除场地信息")
    @PreAuthorize("@ss.hasPermi('concert:site:remove')")
    @Log(title = "场地信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yhSiteService.removeByIds(Arrays.asList(ids)));
    }

    @ApiOperation("通过商家申请")
    @PreAuthorize("@ss.hasPermi('concert:site:pass')")
    @Log(title = "场地信息", businessType = BusinessType.UPDATE)
    @PostMapping("/pass")
    public AjaxResult pass(@RequestBody YhSite yhSite)
    {
        yhSite.setStatus(1);
        return toAjax(yhSiteService.updateById(yhSite));
    }

    // 获取所有场地
    @Anonymous
    @ApiOperation("获取所有场地")
    @GetMapping("/listAll")
    public AjaxResult getAllSite() {

        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        LambdaQueryWrapper<YhSite> yhSiteLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yhSiteLambdaQueryWrapper.eq(YhSite::getUserId,userId);
        yhSiteLambdaQueryWrapper.eq(YhSite::getStatus,1);
        List<YhSite> list = yhSiteService.list(yhSiteLambdaQueryWrapper);
        return AjaxResult.success(list);
    }
}